<?php

namespace App\Http\Controllers\Site\Custom\Provider;

use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Area;
use App\B2BProject\Custom\AuthorizationRequest;
use App\B2BProject\Custom\Business\Goods;
use App\B2BProject\Custom\Business\LicensedGood;
use App\B2BProject\Custom\Business\PriceStrategy;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyPurchaserController extends Controller
{
    use HelperControllerBuildTrait;

    /**
     * 获取授权的采购商列表
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $authorizations = \Auth::user()->providerAuthorizationRequests()->display();

        if ($start = $request->query('startTime')) {
            $authorizations = $authorizations->where('authorize_stop', '>=', date('Y-m-d', strtotime($start)));
        }

        if ($end = $request->query('endTime')) {
            $authorizations = $authorizations->where('authorize_stop', '<=', date('Y-m-d', strtotime($end)));
        }

        if ($name = $request->query('name')) {
            $authorizations = $authorizations->where('company_name', 'like', "%$name%");
        }

        $authorizations = $authorizations->orderBy('created_at',
            'desc')->paginate($request->query('pageSize', 7));

        if ($request->ajax()) {
            $data = [];

            foreach ($authorizations as $authorization) {
                $data[] = [
                    'id'          => $authorization->id,
                    'companyname' => $authorization->company_name,
                    'buyername'   => $authorization->contact_name,
                    'state'       => ['停止授权', '合作中', '过期'][$authorization->getAuthorizationStatus()],
                    'applydate'   => date('Y-m-d', strtotime($authorization->created_at)),
                    'enddate'     => date('Y-m-d', strtotime($authorization->authorize_stop)),
                    'amount'      => $authorization->licensedGoods()->count(),
                    'operate'     => $authorization->process_status == 1 ?: 0,
                    'authoryUrl'  => route('account.member.authorization-request.show', [$authorization->id]),
                    'detailUrl'   => route('account.my-purchaser.licensed', [$authorization->id]),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $authorizations->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $authorizations->total(),
                ],
            ]);
        }

        \Session::put('purchaser_return', 'account.my-purchaser.index');

        return view('host/custom/provider/my-purchaser/index');
    }

    /**
     * 获取商品授权列表
     *
     * @param Request $request
     * @param         $id
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function getIndex(Request $request, $id)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $authorization = AuthorizationRequest::findOrFail($id);

        if ($request->ajax()) {
            $data = [];

            $licenseds
                = $authorization->licensedGoods()->orderBy('created_at',
                'desc')->paginate($request->query('pageSize'));

            foreach ($licenseds as $licensed) {
                $data[] = [
                    'id'         => $licensed->id,
                    'policyname' => $licensed->goods->name,
                    'context'    => $licensed->goods->original_price,
                    'tradeprice' => $licensed->priceStrategy->name .
                                    " ({$licensed->priceStrategy->price_strategies})",
                    'price'      => Area::getName($licensed->province_id) .
                                    ' ' .
                                    Area::getName($licensed->city_id) .
                                    ' ' .
                                    Area::getName($licensed->county_id),
                    'stock'      => ['终止', '合作'][$licensed->status],
                    'status'     => $licensed->status,
                    'edit_url'   => route('account.my-purchaser.licensed.edit', [$id, $licensed->id]),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $licenseds->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $licenseds->total(),
                ],
            ]);
        }

        return view('host/custom/provider/my-purchaser/licensed-index', ['authorization' => $authorization]);
    }

    /**
     * 提交商品授权
     *
     * @param Request $request
     * @param         $id
     * @param         $lid
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function putLicensedEdit(Request $request, $id, $lid)
    {
        $authRequest = \Auth::user()->providerAuthorizationRequests()->whereId($id)->firstOrFail();

        /**
         * @var LicensedGood $licensed
         */
        $licensed = $authRequest->LicensedGoods()->whereId($lid)->firstOrFail();

        $validator = \Validator::make($request->all(), [
            'price'    => 'required|exists:price_strategies,id,store_id,' . \Auth::user()->store->id,
            'province' => 'required|exists:areas,id,level,1',
            'city'     => 'required|exists:areas,id,level,2',
            'country'  => 'required|exists:areas,id,level,3',
        ]);

        if ($validator->fails()) {
            return response($validator->errors(), 403);
        }

        \DB::transaction(function () use ($id, $licensed, $request) {
            $licensed->priceStrategy()->associate(PriceStrategy::findOrFail($request->price));

            $licensed->province_id = $request->province;
            $licensed->city_id     = $request->city;
            $licensed->county_id   = $request->country;

            $licensed->save();
        });

        return redirect()->route('account.my-purchaser.licensed', [$id]);
    }

    /**
     * 进入商品授权编辑页
     *
     * @param $id
     * @param $lid
     *
     * @return $this
     */
    public function getLicensedEdit($id, $lid)
    {
        $authRequest = \Auth::user()->providerAuthorizationRequests()->whereId($id)->firstOrFail();

        $licensed = $authRequest->LicensedGoods()->whereId($lid)->firstOrFail();

        $strategies = \Auth::user()->store->priceStrategy;

        $data = [];
        foreach ($strategies as $strategy) {
            $data[] = [
                'code' => $strategy->id,
                'text' => $strategy->name . " ({$strategy->price_strategies})",
            ];
        }

        return view('host/custom/provider/my-purchaser/licensed-edit')->with('licensed',
            $licensed)->with('authorization', $authRequest)->with('strategies', $data);
    }

    /**
     * 添加一个新的授权商品
     *
     * @param Request $request
     * @param         $id
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function postIndex(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'proids'   => 'required',
            'price'    => 'required|exists:price_strategies,id,store_id,' . \Auth::user()->store->id,
            'province' => 'required|exists:areas,id,level,1',
            'city'     => 'required|exists:areas,id,level,2',
            'country'  => 'required|exists:areas,id,level,3',
        ]);

        if ($validator->fails()) {
            return response('Error', 403);
        }

        try {
            /**
             * @var AuthorizationRequest $authorization
             */
            $authorization = AuthorizationRequest::findOrFail($id);

            \DB::transaction(function () use ($request, $authorization) {
                $priceStrategy = PriceStrategy::findOrFail($request->price);

                foreach (explode(',', $request->proids) as $goods) {
                    $goods = Goods::findOrFail($goods);

                    if ($authorization->licensedGoods()->available()->where('goods_id', $goods->id)->count() > 0) {
                        continue;
                    }

                    $licensed = new LicensedGood();

                    $licensed->priceStrategy()->associate($priceStrategy);
                    $licensed->goods()->associate($goods);
                    $licensed->authorizationRequest()->associate($authorization);

                    $licensed->province_id = $request->province;
                    $licensed->city_id     = $request->city;
                    $licensed->county_id   = $request->country;

                    $licensed->save();
                }
            });

            return $this->getIndex($request, $id);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /**
     * 获取还未被授权的商品列表
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsList($id)
    {
        $authorization = AuthorizationRequest::findOrFail($id);

        $isset = [];

        foreach ($authorization->licensedGoods()->available()->get() as $licensed) {
            $isset[] = $licensed->goods_id;
        }

        $goods = \Auth::user()->store->goods()->whereNotIn('id', $isset)->get();

        $data = [];

        foreach ($goods as $good) {
            $data[] = [
                'id'      => $good->id,
                'img'     => $good->cover(),
                'proname' => $good->name,
                'price'   => $good->original_price,
            ];
        }

        return response()->json(['data' => $data]);
    }

    /**
     * 获取价格策略
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getPriceStrategy()
    {
        $priceStrategy = \Auth::user()->store->priceStrategy;

        $data = [];

        foreach ($priceStrategy as $strategy) {
            $data[] = [
                'code' => $strategy->id,
                'text' => $strategy->name . " ({$strategy->price_strategies})",
            ];
        }

        return response()->json(['data' => $data]);
    }

    /**
     * 终止商品授权
     *
     * @param Request $request
     * @param         $id
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function putIndex(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), ['id' => 'required|exists:licensed_goods,id,status,1']);

        if ($validator->fails()) {
            return response('Error!', 403);
        }

        $authorization = AuthorizationRequest::findOrFail($id);

        $licensed         = $authorization->licensedGoods()->whereId($request->id)->firstOrFail();
        $licensed->status = false;
        $licensed->save();

        return $this->getIndex($request, $id);
    }

    public function putShutdown(Request $request)
    {
        $id = $request->id;

        try {
            $authorizationRequest = \Auth::user()->providerAuthorizationRequests()->where('id', $id)->firstOrFail();
            $authorizationRequest->process_status = 0;
            $authorizationRequest->save();
        } catch (ModelNotFoundException $e) {
            if ($request->ajax()) {
                return response()->json(['选择的采购商请求信息异常'], 403);
            }

            abort(403);
        }

        return $this->index($request);
    }
}
